package com.flight.view;

import com.flight.model.entity.Order;
import com.flight.util.Constant;
import com.flight.view.components.MessageDialog;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.List;

public class OrderManagePanel extends JPanel {
    private String passengerId;
    private JTable orderTable;
    private DefaultTableModel tableModel;
    private List<Order> orderList;
    private JButton backBtn; // 返回主界面按钮

    public OrderManagePanel(String passengerId) {
        this.passengerId = passengerId;
        initUI();
    }

    private void initUI() {
        // 顶部面板（包含标题和返回按钮）
        JPanel topPanel = new JPanel(new BorderLayout());

        JPanel titlePanel = new JPanel();
        titlePanel.add(new JLabel("我的订单"));

        backBtn = new JButton("返回主界面");
        JPanel backPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        backPanel.add(backBtn);

        topPanel.add(titlePanel, BorderLayout.WEST);
        topPanel.add(backPanel, BorderLayout.EAST);
        add(topPanel, BorderLayout.NORTH);
//        setLayout(new BorderLayout());
//
//        JPanel titlePanel = new JPanel();
//        titlePanel.add(new JLabel("我的订单"));
//        add(titlePanel, BorderLayout.NORTH);

        String[] columnNames = {"订单号", "金额（元）", "状态", "操作"};
        tableModel = new DefaultTableModel(null, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 3;
            }
        };
        orderTable = new JTable(tableModel);
        // 修正：设置自定义渲染器和编辑器（实现TableCellRenderer/Editor接口）
        orderTable.getColumnModel().getColumn(3).setCellRenderer(new ButtonRenderer());
        orderTable.getColumnModel().getColumn(3).setCellEditor(new ButtonEditor(new JCheckBox()));
        add(new JScrollPane(orderTable), BorderLayout.CENTER);
    }

    // 新增：绑定返回主界面按钮事件
    public void addBackListener(ActionListener listener) {
        backBtn.addActionListener(listener);
    }

    /**
     * 更新订单列表数据
     */
    public void setOrderData(List<Order> orders) {
        this.orderList = orders;
        tableModel.setRowCount(0); // 清空现有数据
        if (orders.isEmpty()) {
            MessageDialog.showInfo(this, "暂无订单");
            return;
        }
        for (Order order : orders) {
            String status = getStatusText(order.getPayStatus());
            String operation = getOperationText(order.getPayStatus());
            Object[] rowData = {
                    order.getOrderId(),
                    order.getOrderAmount(),
                    status,
                    operation
            };
            tableModel.addRow(rowData);
        }
    }

    /**
     * 绑定操作按钮事件（支付/退票）
     */
    public void setOperationActionListener(ActionListener listener) {
        ((ButtonEditor) orderTable.getColumnModel().getColumn(3).getCellEditor()).setActionListener(listener);
    }

    /**
     * 获取选中的订单
     */
    public Order getSelectedOrder() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow < 0 || selectedRow >= orderList.size()) {
            MessageDialog.showError(this, "请选择订单");
            return null;
        }
        return orderList.get(selectedRow);
    }

    // 状态文本转换（0→未付款，1→已付款，2→已退款）
    private String getStatusText(int status) {
        switch (status) {
            case Constant.ORDER_STATUS_UNPAID: return "未付款";
            case Constant.ORDER_STATUS_PAID: return "已付款";
            case Constant.ORDER_STATUS_REFUNDED: return "已退款";
            default: return "未知状态";
        }
    }

    // 操作文本转换（未付款→支付，已付款→退票，已退款→不可操作）
    private String getOperationText(int status) {
        switch (status) {
            case Constant.ORDER_STATUS_UNPAID: return "支付";
            case Constant.ORDER_STATUS_PAID: return "退票";
            default: return "无";
        }
    }

    // 修正按钮渲染器：继承DefaultTableCellRenderer
    private static class ButtonRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
        private JButton button;

        public ButtonRenderer() {
            button = new JButton();
            button.setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            button.setText((value == null) ? "" : value.toString());
            return button;
        }
    }

    // 修正按钮编辑器：实现TableCellEditor接口
    private static class ButtonEditor extends AbstractCellEditor implements TableCellEditor {
        private JButton button;
        private ActionListener actionListener;
        private Object value;

        public ButtonEditor(JCheckBox checkBox) {
            button = new JButton();
            button.setOpaque(true);
            button.addActionListener(e -> {
                fireEditingStopped();
                if (actionListener != null) {
                    actionListener.actionPerformed(e);
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            this.value = value;
            button.setText((value == null) ? "" : value.toString());
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            return value;
        }

        public void setActionListener(ActionListener listener) {
            this.actionListener = listener;
        }
    }
}